use std::fs;
use std::path::PathBuf;
use symlink::symlink_file;

pub fn delete_symlink_in_dir(symlink_path_roor_dir: &str) -> Result<(), anyhow::Error> {
    let symlink_dir = PathBuf::from(symlink_path_roor_dir);
    if symlink_dir.exists() && symlink_dir.is_dir() {
        for entry in fs::read_dir(&symlink_dir)? {
            let entry = entry?;
            let path = entry.path();

            let metadata = fs::metadata(&path)?;
            let file_type = metadata.file_type();

            if file_type.is_symlink() {
                let _ = fs::remove_file(&path); // 删除掉symlink的引用
            }
        }
        Ok(())
    } else {
        anyhow::bail!(
            "custom_file_symlink parameter error: symlink_path_roor_dir:{:?}",
            symlink_path_roor_dir
        );
    }
}

pub fn custom_file_symlink(
    file_path: &str,
    symlink_path_roor_dir: &str,
) -> Result<String, anyhow::Error> {
    let origin_file_path = PathBuf::from(file_path);
    let symlink_dir = PathBuf::from(symlink_path_roor_dir);
    if origin_file_path.exists()
        && origin_file_path.is_file()
        && symlink_dir.exists()
        && symlink_dir.is_dir()
    {
        let file_name = origin_file_path
            .file_name()
            .unwrap()
            .to_str()
            .unwrap()
            .to_owned();

        let symlink_file_path = symlink_dir.join(file_name.clone());
        if symlink_file_path.exists() {
            let symlink_file_path_name = symlink_file_path.to_str().unwrap().to_owned();
            log::warn!(
                "custom_file_symlink symlink_file success = {:?}",
                symlink_file_path_name
            );
            Ok(file_name)
        } else {
            match symlink_file(&origin_file_path, &symlink_file_path) {
                Ok(_) => {
                    let symlink_file_path_name = symlink_file_path.to_str().unwrap().to_owned();
                    log::warn!(
                        "custom_file_symlink symlink_file success = {:?}",
                        symlink_file_path_name
                    );
                    Ok(file_name)
                }
                Err(e) => {
                    anyhow::bail!("custom_file_symlink symlink_file error = {:?}", e)
                }
            }
        }
    } else {
        anyhow::bail!(
            "custom_file_symlink parameter error: file_path:{:?},symlink_path_roor_dir:{:?}",
            file_path,
            symlink_path_roor_dir
        );
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn test_custom_file_symlink() {
        use crate::utils::logutil;
        use crate::utils::symbol_link_util;
        logutil::global_log_init("DEBUG");
        let origin_file = r#"/Users/ricolv/Downloads/log.txt"#;
        let root_dir = r#"/Users/ricolv/Downloads/yuv"#;
        if let Err(e) = symbol_link_util::custom_file_symlink(origin_file, root_dir) {
            log::error!("custom_file_symlink error: {:?}", e);
        }
    }
}
